import { createRouter, createWebHistory } from 'vue-router';
import Login from '../components/LoginNew.vue';

// 懒加载路由组件
const Layout = () => import('../components/layout/Layout.vue');
const Dashboard = () => import('../views/dashboard/Dashboard.vue');
const DeviceList = () => import('../views/device/DeviceList.vue');
const DataAnalysis = () => import('../views/analysis/DataAnalysis.vue');
const AlarmManage = () => import('../views/alarm/AlarmManage.vue');
const UserSettings = () => import('../views/setting/UserSettings.vue');
const ApiDebug = () => import('../views/debug/ApiDebug.vue');

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录', noAuth: true }
  },
  {    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '仪表盘', icon: 'DataBoard' }
      },
      {
        path: 'device',
        name: 'DeviceList',
        component: DeviceList,
        meta: { title: '设备管理', icon: 'Monitor' }
      },
      {
        path: 'analysis',
        name: 'DataAnalysis',
        component: DataAnalysis,
        meta: { title: '数据分析', icon: 'TrendCharts' }
      },
      {
        path: 'alarm',
        name: 'AlarmManage',
        component: AlarmManage,
        meta: { title: '告警管理', icon: 'Warning' }
      },
      {
        path: 'settings',
        name: 'UserSettings',
        component: UserSettings,
        meta: { title: '系统设置', icon: 'Setting' }
      },      {
        path: 'debug',
        name: 'ApiDebug',
        component: ApiDebug,
        meta: { title: 'API调试', icon: 'Connection' }
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 导航守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 空气质检仪管理系统` : '空气质检仪管理系统';
  
  const token = localStorage.getItem('token');
  
  // 如果访问的不是登录页，且没有token，则重定向到登录页
  if (to.path !== '/login' && !token) {
    next('/login');
  } else {
    next();
  }
});

export default router;
